URL = "http://kent.dl.sourceforge.net/sourceforge/loki-lib/loki-%(VERSION)s.tar.gz"
VERSIONS = ["0.1.7"]
DEFAULT_VERSION = "0.1.7"

import os
from source.builders import ConfigureMakeBuilder, VisualStudioBuilder

class LokiConfigureMakeBuilder( ConfigureMakeBuilder ):
  """ subclass of ConfigureMakeBuilder with custom configure step """

  def configure(self ):
    """configure loki, change the prefix in the Makefile.common """
    os.chdir( self.extractedpath )

    input_file = 'Makefile.common'
    temp_file = 'Makefile.temp'
    input = open(input_file, 'r')
    output = open(temp_file, 'w')
    for s in input.xreadlines():
      output.write(s.replace("/usr", self.installpath()))
    input.close()
    output.close()
    os.rename(temp_file, input_file)


class LokiBatchFileBuilder( VisualStudioBuilder ):
  def installpath(self):
    return os.path.join(self.extractedpath, "binaries")

  def make_msvcbat(self ):
    #now switched to make using devenv
    os.chdir( self.extractedpath)
    if self.machine.isVS2008():
      self.replaceInFile( "make.msvc.bat", [ ("VS80COMNTOOLS", "VS90COMNTOOLS") ] )
      #dont call vsvars (this should be done by the user)
      replacements = [( ".*call \"%VS90COMNTOOLS%\\\\vsvars32.bat\"", "rem call \"%VS90COMNTOOLS%\\vsvars32.bat\"" )]
      self.replaceLinesInFile( "make.msvc.bat", replacements )
    else:
      replacements = [( ".*call \"%VS90COMNTOOLS%\\\\vsvars32.bat\"", "rem call \"%VS90COMNTOOLS%\\vsvars32.bat\"" )]
      self.replaceLinesInFile( "make.msvc.bat", replacements )    
    self.execute( "make.msvc.bat" )

  def make(self ):
    os.chdir( self.extractedpath)
    if self.machine.isVS2008():
      self.solution = "Loki_MSVC_9.sln"
      self.proj = "src/Library_MSVC9.vcproj"
    else:
      self.solution = "Loki_MSVC_8.sln"
      self.proj = "src/Library_MSVC_8.vcproj"
    if self.machine.bits == 64:
      self.convertProjTo64(self.proj)
      self.convertSolutionTo64(self.solution)

    self.debug = True; self.call_devenv(self.solution, "Library")
    self.debug = False; self.call_devenv(self.solution, "Library")
    
  def copy( self ):
    self.copydir( self.extractedpath + "/include", self.targetpath() + "/include" )
    self.copydir( self.extractedpath + "/lib", self.targetpath() + "/lib" )


def decider( machine, dirs ):
  """build and install loki in the enviro/machine directory"""
  if machine.isWindows():
    return LokiBatchFileBuilder
  else:
    return LokiConfigureMakeBuilder


BUILDER = decider
